package com.gxa.saas.portal.service.impl;

import com.gxa.saas.core.vo.GoodsVo;
import com.gxa.saas.portal.mapper.AppInfoMapper;
import com.gxa.saas.portal.service.AddJestService;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.core.Bulk;
import io.searchbox.core.Delete;
import io.searchbox.core.Index;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("addJestService")
public class AddJestServiceImpl implements AddJestService {

    @Autowired
    private JestClient jestClient;

    @Autowired
    private AppInfoMapper appInfoMapper;

    private static final String INDEX="goods_table3";

    private static final String TYPE="_doc";

//    * 手动增加测试数据
//	 * 实际中可以使用定时任务同步，或者logstash

    public void add() {
        List<GoodsVo> appInfoList = appInfoMapper.selectGoods();
        Bulk.Builder bulk = new Bulk.Builder();
        for (GoodsVo goodsVo : appInfoList) {
            Index index = new Index.Builder(goodsVo).index(INDEX).id(String.valueOf(goodsVo.getPrId())).build();
            bulk.addAction(index);
        }

        try {
            JestResult jestResult = jestClient.execute(bulk.build());
//            System.out.println(jestResult.getJsonString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void newAdd(String prId) {
        List<GoodsVo> appInfoList = appInfoMapper.NewselectGoods(prId);
        Bulk.Builder bulk = new Bulk.Builder();
        for (GoodsVo goodsVo : appInfoList) {
            Index index = new Index.Builder(goodsVo).index(INDEX).id(String.valueOf(goodsVo.getPrId())).build();
            bulk.addAction(index);
        }

        try {
            JestResult jestResult = jestClient.execute(bulk.build());
//            System.out.println(jestResult.getJsonString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void delete(String uuid) {
        Delete delete = new Delete.Builder(uuid).index(INDEX).type(TYPE).build();

        try {
            JestResult jestResult = jestClient.execute(delete);
//            System.out.println(jestResult.getJsonString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
